package com.shop.cloud.controller.shop;

import io.swagger.annotations.ApiOperation;

import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;

import com.shop.cloud.JPush.MsgPushUtils;
import com.shop.cloud.common.mybatis.BaseController;
import com.shop.cloud.dao.hongfu.ShopDao;
import com.shop.cloud.domain.hongfu.City;
import com.shop.cloud.domain.hongfu.Message;
import com.shop.cloud.domain.hongfu.Province;
import com.shop.cloud.domain.hongfu.Region;
import com.shop.cloud.domain.hongfu.Shop;
import com.shop.cloud.domain.hongfu.ShopAptitude;
import com.shop.cloud.domain.hongfu.ShopImage;
import com.shop.cloud.domain.hongfu.ShopType;
import com.shop.cloud.domain.hongfu.StoreApplication;
import com.shop.cloud.domain.hongfu.SysConfig;
import com.shop.cloud.filter.CurrentUserId;
import com.shop.cloud.model.request.AddSelfShopRequest;
import com.shop.cloud.model.request.AddShopTypeRequest;
import com.shop.cloud.model.request.CheckEnterShopRequest;
import com.shop.cloud.model.request.CloseEnterShopRequest;
import com.shop.cloud.model.request.CloseSelfShopRequest;
import com.shop.cloud.model.request.DeleteShopTypeRequest;
import com.shop.cloud.model.request.EditEnterShopRequest;
import com.shop.cloud.model.request.EditSelfShopRequest;
import com.shop.cloud.model.request.EditShopTypeRequest;
import com.shop.cloud.model.request.GetEnterShopListRequest;
import com.shop.cloud.model.request.GetSelfShopListRequest;
import com.shop.cloud.model.request.GetShopTypeListRequest;
import com.shop.cloud.model.request.ViewEnterShopRejectedReasonRequest;
import com.shop.cloud.model.response.AddSelfShopResponse;
import com.shop.cloud.model.response.AddShopTypeResponse;
import com.shop.cloud.model.response.CheckEnterShopResponse;
import com.shop.cloud.model.response.CloseEnterShopResponse;
import com.shop.cloud.model.response.CloseSelfShopResponse;
import com.shop.cloud.model.response.DeleteShopTypeResponse;
import com.shop.cloud.model.response.EditEnterShopResponse;
import com.shop.cloud.model.response.EditSelfShopResponse;
import com.shop.cloud.model.response.EditShopTypeResponse;
import com.shop.cloud.model.response.GetEnterShopListResponse;
import com.shop.cloud.model.response.GetSelfShopListResponse;
import com.shop.cloud.model.response.GetShopTypeListResponse;
import com.shop.cloud.model.response.ViewEnterShopRejectedReasonResponse;
import com.shop.cloud.service.hongfu.IStoreApplicationService;
import com.shop.cloud.service.hongfu.impl.CityService;
import com.shop.cloud.service.hongfu.impl.MessageService;
import com.shop.cloud.service.hongfu.impl.ProvinceService;
import com.shop.cloud.service.hongfu.impl.RegionService;
import com.shop.cloud.service.hongfu.impl.ShopAptitudeService;
import com.shop.cloud.service.hongfu.impl.ShopImageService;
import com.shop.cloud.service.hongfu.impl.ShopService;
import com.shop.cloud.service.hongfu.impl.ShopTypeService;
import com.shop.cloud.service.hongfu.impl.SysConfigService;
import com.shop.cloud.util.ErrorCode;
import com.shop.cloud.util.Page;
import com.shop.cloud.util.Response;
import com.shop.cloud.util.ResponseUtil;

@RestController
@RequestMapping(value = "shop")
public class ShopController extends BaseController {

	private static final Logger logger = Logger.getLogger(ShopController.class);

	@Autowired
	private ShopService shopService;
	
	@Autowired
	private ShopTypeService shopTypeService;
	
	@Autowired
	private ShopImageService shopImageService;
	
	@Autowired
	private RegionService regionService;
	
	@Autowired
	private ShopAptitudeService shopAptitudeService;
	
	@Autowired
	private SysConfigService sysConfigService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private ProvinceService provinceService;
	
	@Autowired
	private ShopDao shopDao;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private IStoreApplicationService storeApplicationService;


	//@MagicPermission
	@ApiOperation(value = "获取自营店铺列表", notes = "获取自营店铺列表")
	@RequestMapping(value = "selfShopList", method = RequestMethod.POST)
	@ResponseBody
	public Response selfShopList(HttpServletRequest request, HttpServletResponse response,@CurrentUserId Long userId,@RequestBody GetSelfShopListRequest selfShopListRequest) {
		logger.debug("获取自营店铺列表");
		List<GetSelfShopListResponse> datas = new ArrayList<GetSelfShopListResponse>();
		GetSelfShopListResponse data = null;
		Map<String, Object> params = getPageMap(request);
		
		//用户权限
		Shop shop2 = shopDao.getRoleId(userId);
		if (shop2.getAuthority()==1) {
//			params.put("roleId",shop2.getRoleId());
		}
		
		if (shop2.getAuthority()==2) {
			params.put("roleId",shop2.getRoleId());
		}
		
		//查询条件
		if(!(selfShopListRequest.getStartTime() == null || selfShopListRequest.getStartTime().equals(""))){
			params.put("startTime", selfShopListRequest.getStartTime());
		}
		if(!(selfShopListRequest.getEndTime() == null || selfShopListRequest.getEndTime().equals(""))){
			params.put("endTime", selfShopListRequest.getEndTime());
		}
		if (selfShopListRequest.getName() != null && !selfShopListRequest.getName().trim().equals("")) {
			params.put("name", selfShopListRequest.getName());
		}
		if (selfShopListRequest.getStatus()!=null) {
			params.put("status", selfShopListRequest.getStatus());
		}
		params.put("isUnion", 2);
		
		List<Shop> shops = null;
		Shop shop = null;
//		分页
		long count = shopService.count(params);
		int pageIndex = selfShopListRequest.getPageIndex_();
		int pageSize = selfShopListRequest.getPageSize_();
		Page<GetSelfShopListResponse> page = new Page<GetSelfShopListResponse>(pageIndex,pageSize);
		int limitStart = (pageIndex - 1) * pageSize;
		params.put("limitStart", limitStart);
		
		int limitEnd = pageSize;
		params.put("limitEnd", limitEnd);
		params.put("orderBy", "SHOP.create_time desc");
		params.put("exist", 0);
		shops = shopService.find(params);
		
		if (shops != null) { 
			for (int i = 0; i < shops.size(); i++) {
				shop = shops.get(i);
				data = new GetSelfShopListResponse();
				data.setId(shop.getId());
				data.setName(shop.getName()); 
				
				//经纬度
				data.setLongitude(shop.getLongitude());
				data.setLatitude(shop.getLatitude());
				
				ShopImage shopImage = new ShopImage();
				shopImage.setShopId(shop.getId());
				List<ShopImage> listShopImage = shopImageService.find(shopImage);
				List<String> listImage = new ArrayList<String>();
				if (listShopImage != null && listShopImage.size() > 0) {
					for (ShopImage si : listShopImage) {
						listImage.add(si.getImage());
					}
				}
				logger.debug("商家图片数量： "+listImage.size());
				data.setPic(listImage);
				data.setIntroduce(shop.getIntroduce());

				ShopType shopType = new ShopType();
				shopType.setId(shop.getTypeId());
				List<ShopType> listShopType = shopTypeService.find(shopType);
				if (listShopType != null && listShopType.size() != 0) {
					String shopTypeName = listShopType.get(0).getName();
					data.setTypeId(listShopType.get(0).getId());
					data.setTypeStr(shopTypeName);
				}

				data.setStatusStr(String.valueOf(shop.getStatus()));
				data.setPhone(shop.getPhone());
				
				Region resultRegion = null;
				City resultCity = null;
				Province resultProvince = null;
				
				if (shop.getRegionId() != null && !shop.getRegionId().equals("")) {
					Region region = new Region();
					region.setId(shop.getRegionId());
					resultRegion = regionService.findOne(region);
					
				}
				if (resultRegion.getCityId() != null && !resultRegion.getCityId().equals("")) {
					City city = new City();
					city.setId(resultRegion.getCityId());
					resultCity = cityService.findOne(city);
				}
				
				if (resultCity.getProvinceId() != null && !resultCity.getProvinceId().equals("")) {
					Province province = new Province();
					province.setId(resultCity.getProvinceId());
					resultProvince = provinceService.findOne(province);
				}
				
				data.setProvinceId(resultProvince.getId());
				data.setCityId(resultCity.getId());
				data.setRegionId(resultRegion.getId());
				data.setProvinceStr(resultProvince.getName());
				data.setCityStr(resultCity.getName());
				data.setRegionStr(resultRegion.getName());
				data.setAddress(shop.getAddress());
				data.setOpenTime(new SimpleDateFormat("HH:mm").format(shop.getOpenStartTime()) + " - " + new SimpleDateFormat("HH:mm").format(shop.getOpenEndTime()) );
				data.setStartTime(new SimpleDateFormat("HH:mm").format(shop.getOpenStartTime()) );
				data.setEndTime(new SimpleDateFormat("HH:mm").format(shop.getOpenEndTime()) );
				
				ShopAptitude shopAptitude = new ShopAptitude();
				shopAptitude.setShopId(shop.getId());
				List<ShopAptitude> listShopAptitude = shopAptitudeService.find(shopAptitude);
				
				List<String> resultListAptitude = new ArrayList<String>();
				if (listShopAptitude != null && listShopAptitude.size() > 0) {
					for (ShopAptitude sa : listShopAptitude) {
						resultListAptitude.add(sa.getImage());
					}
				}
				logger.debug("资质图片数量： "+resultListAptitude.size());
				data.setAptitudeImage(resultListAptitude);
				data.setCreateTime(shop.getCreateTime());
				
				datas.add(data);
			}
		}
		page.setData(datas);
		page.setTotalCount((int)count);
		
		return ResponseUtil.ok(page);
	}
	 
	//@MagicPermission
	@ApiOperation(value = "添加自营店铺", notes = "添加自营店铺")
	@RequestMapping(value = "addSelfShop", method = RequestMethod.POST)
	@ResponseBody
	public Response addSelfShop(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody AddSelfShopRequest addSelfShopRequest){
		AddSelfShopResponse addSelfShopResponse = new AddSelfShopResponse();
		Shop shop = new Shop();
		ShopImage shopImage = new ShopImage();
		ShopAptitude shopAptitude = new ShopAptitude();
		logger.debug("添加自营店铺");
		List<String> listImages = addSelfShopRequest.getPics();
		List<String> listAptitudes = addSelfShopRequest.getAptitudeImages();
		Region region = new Region();
		region.setCityId(addSelfShopRequest.getCityId());
		region.setName(addSelfShopRequest.getName());
		regionService.insert(region);
		
//		shopId 如果是自营店铺的话，这个值是0；如果是加盟店铺，就和user表里的id对应
		shop.setUserId(0L);
		shop.setName(addSelfShopRequest.getName()); 
		shop.setIntroduce(addSelfShopRequest.getIntroduce());
		shop.setTypeId(addSelfShopRequest.getTypeId());
		shop.setPhone(addSelfShopRequest.getPhone());
		shop.setRegionId(addSelfShopRequest.getRegionId());
		shop.setAddress(addSelfShopRequest.getAddress());
		//门店Id
		shop.setRoleId(addSelfShopRequest.getRoleId());
		//经纬度
		shop.setLatitude(addSelfShopRequest.getLatitude());
		shop.setLongitude(addSelfShopRequest.getLongitude());
		if (addSelfShopRequest.getStart_time() == null || addSelfShopRequest.getStart_time().equals("")) {
			shop.setOpenStartTime(Time.valueOf("00:00:00"));
		}else {
			String str = addSelfShopRequest.getStart_time();
			str = str.substring(11);
			shop.setOpenStartTime(Time.valueOf(str));
		}
		if (addSelfShopRequest.getEnd_time() == null || addSelfShopRequest.getEnd_time().equals("")) {
			shop.setOpenEndTime(Time.valueOf("23:59:59"));
		}else {
			String str = addSelfShopRequest.getEnd_time();
			str = str.substring(11);
			shop.setOpenEndTime(Time.valueOf(str));
		}
		shop.setCreateTime(new Timestamp(System.currentTimeMillis()));
		shop.setUpdateTime(new Timestamp(System.currentTimeMillis()));
		shop.setIsOfficial(1);
		shop.setIsUnion(2);
		shop.setStatus(Shop.STATUS_OK);
		
		
		if(!shopService.insert(shop)) {
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR, "添加失败");
		}
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("orderBy", "create_time desc");
		shop = shopService.findOne(params);
		
		for (String str : listImages) {
			shopImage.setImage(str);
			shopImage.setShopId(shop.getId());
			shopImageService.insert(shopImage);
		}
		
		for (String str : listAptitudes) {
			shopAptitude.setShopId(shop.getId());
			shopAptitude.setImage(str);
			shopAptitudeService.insert(shopAptitude);
		}
		
		return ResponseUtil.ok(addSelfShopResponse);
	}
	
	//@MagicPermission
	@ApiOperation(value = "更新自营店铺", notes = "更新自营店铺")
	@RequestMapping(value = "updateSelfShop", method = RequestMethod.POST)
	@ResponseBody
	public Response updateSelfShop(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody EditSelfShopRequest editSelfShopRequest){
		EditSelfShopResponse editSelfShopResponse = new EditSelfShopResponse();
		Shop shop = new Shop();
		Map<String, Object> params = null;
		logger.debug("更新自营店铺");
//		shopId 如果是自营店铺的话，这个值是0；如果是加盟店铺，就和user表里的id对应
		
		ShopImage shopImage = new ShopImage();
		ShopAptitude shopAptitude = new ShopAptitude();
		
		//清空图片再添加
		params = new HashMap<String, Object>();
		params.put("shopId", editSelfShopRequest.getId());
		shopImageService.remove(params);
		shopAptitudeService.remove(params);
		List<String> listImages = editSelfShopRequest.getPics();
		for (String str : listImages) {
			shopImage = new ShopImage();
			shopImage.setImage(str);
			shopImage.setShopId(Long.parseLong(editSelfShopRequest.getId()));
			shopImageService.insert(shopImage);
		}
		List<String> listAptitudes = editSelfShopRequest.getAptitudeImages();
		for (String str : listAptitudes) {
			shopAptitude = new ShopAptitude();
			shopAptitude.setShopId(Long.parseLong(editSelfShopRequest.getId()));
			shopAptitude.setImage(str);
			shopAptitudeService.insert(shopAptitude);
		}
		
		Region region = new Region();
		region.setCityId(editSelfShopRequest.getCityId());
		region.setName(editSelfShopRequest.getName());
		regionService.update(region);
		
		shop.setId(Long.valueOf(editSelfShopRequest.getId()));
		shop.setName(editSelfShopRequest.getName());
		shop.setIntroduce(editSelfShopRequest.getIntroduce());
		shop.setTypeId(editSelfShopRequest.getTypeId());
		shop.setPhone(editSelfShopRequest.getPhone());
		shop.setRegionId(editSelfShopRequest.getRegionId());
		shop.setAddress(editSelfShopRequest.getAddress());
		//营业时间
		String str = editSelfShopRequest.getEnd_time();
		str = str.substring(11);
		shop.setOpenEndTime(Time.valueOf(str));
		String str2 = editSelfShopRequest.getStart_time();
		str2 = str2.substring(11);
		shop.setOpenStartTime(Time.valueOf(str2));
		//经纬度
		shop.setLongitude(editSelfShopRequest.getLongitude());
		shop.setLatitude(editSelfShopRequest.getLatitude());
		//门店ID
		shop.setRoleId(editSelfShopRequest.getRoleId());
		
		int line = shopService.update(shop);
		if(line<=0){
			return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR,"更新失败！");
		}
		
		return ResponseUtil.ok(editSelfShopResponse);
	}
	
	//@MagicPermission
	@ApiOperation(value = "关闭自营店铺", notes = "关闭自营店铺")
	@RequestMapping(value = "closeSelfShop", method = RequestMethod.POST)
	@ResponseBody
	public Response colseSelfShop(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody CloseSelfShopRequest closeSelfShopRequest){
		CloseSelfShopResponse closeSelfShopResponse = new CloseSelfShopResponse();
		Shop shop = new Shop();
		logger.debug("关闭自营店铺");
		shop.setId(Long.valueOf(closeSelfShopRequest.getId()));
		shop.setStatus(4);
		
		int line = shopService.update(shop);
		if(line<=0){
			return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR,"关闭失败！");
		}
		
		return ResponseUtil.ok(closeSelfShopResponse);
	}
	
	//@MagicPermission
	@ApiOperation(value = "获取加盟店铺列表", notes = "获取加盟店铺列表")
	@RequestMapping(value = "enterShopList", method = RequestMethod.POST)
	@ResponseBody
	public Response enterShopList(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody GetEnterShopListRequest getEnterShopListRequest){
		logger.debug("获取加盟店铺列表");
		GetEnterShopListResponse data = null;
		List<GetEnterShopListResponse> datas = new ArrayList<GetEnterShopListResponse>();
		Map<String, Object> params = getPageMap(request);
	
		
		List<ShopImage> shopImages = null;
		List<ShopAptitude> shopAptitudes = null;
		List<Shop> shops = null;
		Shop shop = null;
		String pic = null;
		String aptitude = null;
		
//		查询条件
		if(!(getEnterShopListRequest.getStart_time() == null || getEnterShopListRequest.getStart_time().equals(""))){
			params.put("startTime", getEnterShopListRequest.getStart_time());
		}
		if(!(getEnterShopListRequest.getEnd_time() == null || getEnterShopListRequest.getEnd_time().equals(""))){
			params.put("endTime", getEnterShopListRequest.getEnd_time());
		}
		if (getEnterShopListRequest.getName() != null && !getEnterShopListRequest.getName().trim().equals("")) {
			params.put("name", getEnterShopListRequest.getName());
		}
		
		if (getEnterShopListRequest.getType() > 0) {
			params.put("typeId", getEnterShopListRequest.getType());
		}
		if (getEnterShopListRequest.getStatus() > 0) {
			params.put("status", getEnterShopListRequest.getStatus());
		}
		
		params.put("isUnion", 1);
//		if(getEnterShopListRequest.getKeyword() != null && !getEnterShopListRequest.getKeyword().equals("")) {
//			params.put("keyword", getEnterShopListRequest.getKeyword());
//		}
//		if(!(getEnterShopListRequest.getStart_time() == null || getEnterShopListRequest.getStart_time().equals(""))) 
//			params.put("startTime", getEnterShopListRequest.getStart_time());
//		if(!(getEnterShopListRequest.getEnd_time() == null || getEnterShopListRequest.getEnd_time().equals("")))
//			params.put("endTime", getEnterShopListRequest.getEnd_time());
		
		//分页
		long count = shopService.count(params);
		int pageIndex = getEnterShopListRequest.getPageIndex_();
		int pageSize = getEnterShopListRequest.getPageSize_();
		Page<GetEnterShopListResponse> page = new Page<GetEnterShopListResponse>(pageIndex,pageSize);
		int limitStart = (pageIndex - 1) * pageSize;
		params.put("limitStart", limitStart);
		
		int limitEnd = pageSize;
		params.put("limitEnd", limitEnd);
		params.put("orderBy", "SHOP.create_time desc");
		shops = shopService.find(params);
		
		if (shops != null) {
			for (int i = 0; i < shops.size(); i++) {
				List<String> pics = new ArrayList<String>();
				List<String> aptitudes = new ArrayList<String>();
				data = new GetEnterShopListResponse();
				shop = shops.get(i);
				data.setId(shop.getId());
				data.setName(shop.getName()); 
				data.setPic(new ArrayList<>());
				data.setIntroduce(shop.getIntroduce());
				
				ShopType shopType = new ShopType();
				shopType.setId(shop.getTypeId());
				List<ShopType> listShopType = shopTypeService.find(shopType);
				if (listShopType != null && listShopType.size() != 0) {
					String shopTypeName = listShopType.get(0).getName();
					data.setTypeId(listShopType.get(0).getId());
					data.setTypeStr(shopTypeName);
				}
				
				Region resultRegion = null;
				City resultCity = null;
				Province resultProvince = null;
				
				if (shop.getRegionId() != null && !shop.getRegionId().equals("")) {
					Region region = new Region();
					region.setId(shop.getRegionId());
					resultRegion = regionService.findOne(region);
					
					
					if (resultRegion!=null &&resultRegion.getCityId() != null && !resultRegion.getCityId().equals("")) {
						City city = new City();
						city.setId(resultRegion.getCityId());
						resultCity = cityService.findOne(city);
						data.setRegionId(resultRegion.getId());
						data.setRegionStr(resultRegion.getName());
						
					}
					
					if (resultCity!=null && resultCity.getProvinceId() != null && !resultCity.getProvinceId().equals("")) {
						Province province = new Province();
						province.setId(resultCity.getProvinceId());
						resultProvince = provinceService.findOne(province);
						data.setCityId(resultCity.getId());
						data.setCityStr(resultCity.getName());
						if (resultProvince!=null) {
							data.setProvinceId(resultProvince.getId());
							data.setProvinceStr(resultProvince.getName());
						}
					}
				}
				
				//经纬度
				data.setLongitude(shop.getLongitude());
				data.setLatitude(shop.getLatitude());
				data.setStatusStr(String.valueOf(shop.getStatus()));
				data.setPhone(shop.getPhone());
				data.setAddress(shop.getAddress());
				data.setOpenTime(new SimpleDateFormat("HH:mm").format(shop.getOpenStartTime()) + " - " + new SimpleDateFormat("HH:mm").format(shop.getOpenEndTime()) );
				data.setStartTime(new SimpleDateFormat("HH:mm").format(shop.getOpenStartTime()) );
				data.setEndTime(new SimpleDateFormat("HH:mm").format(shop.getOpenEndTime()) );
				params = new HashMap<String, Object>();
				params.put("shopId", shop.getId());
				shopImages = shopImageService.find(params);
				shopAptitudes = shopAptitudeService.find(params);
				
				for(ShopImage shopImage : shopImages) {
					pic = new String(shopImage.getImage()); 
					pics.add(pic);
				}
				data.setPic(pics);
				
				for(ShopAptitude shopAptitude : shopAptitudes) {
					aptitude = new String(shopAptitude.getImage()); 
					aptitudes.add(aptitude);
				}
				data.setAptitudeImage(aptitudes);
				data.setCreateTime(shop.getCreateTime());
				
				datas.add(data);
			}
		}
		
		page.setData(datas);
		page.setTotalCount((int)count);
				 
		return ResponseUtil.ok(page);
	}
	
	//@MagicPermission
	@ApiOperation(value = "更新加盟店铺", notes = "更新自营店铺")
	@RequestMapping(value = "updateEnterShop", method = RequestMethod.POST)
	@ResponseBody
	public Response editEnterShop(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody EditEnterShopRequest editEnterShopRequest){
		
		EditEnterShopResponse editEnterShopResponse = new EditEnterShopResponse();
		System.out.println(editEnterShopRequest.getStart_time());
//		shopId 如果是自营店铺的话，这个值是0；如果是加盟店铺，就和user表里的id对应
		Shop shop = new Shop();
		ShopImage shopImage = new ShopImage();
		ShopAptitude shopAptitude = new ShopAptitude();
		logger.debug("更新加盟店铺");
		List<String> listImages = editEnterShopRequest.getPics();
		Map<String, Object> paramss = new HashMap<String, Object>();
		paramss.put("shopId", editEnterShopRequest.getId());
		shopImageService.remove(paramss);
		for (String str : listImages) {
			shopImage.setImage(str);
			shopImage.setShopId(editEnterShopRequest.getId());
			shopImageService.insert(shopImage);
		}
		
		List<String> listAptitudes = editEnterShopRequest.getAptitudeImages();
		for (String str : listAptitudes) {
			shopAptitude.setShopId(editEnterShopRequest.getId());
			shopAptitude.setImage(str);
			shopAptitudeService.update(shopAptitude);
		}
		
		Region region = new Region();
		region.setCityId(editEnterShopRequest.getCityId());
		region.setName(editEnterShopRequest.getName());
		regionService.update(region);
		
		shop.setId(Long.valueOf(editEnterShopRequest.getId()));
		shop.setName(editEnterShopRequest.getName());
		shop.setIntroduce(editEnterShopRequest.getIntroduce());
		shop.setTypeId(editEnterShopRequest.getTypeId());
		shop.setPhone(editEnterShopRequest.getPhone());
		shop.setRegionId(editEnterShopRequest.getRegionId());
		shop.setAddress(editEnterShopRequest.getAddress());
		shop.setStartTime(editEnterShopRequest.getStartTime());
		shop.setEndTime(editEnterShopRequest.getEndTime());
		shop.setStatus(editEnterShopRequest.getStatus());
		
		//营业时间
		String str = editEnterShopRequest.getEnd_time();
		str = str.substring(11);
		shop.setOpenEndTime(Time.valueOf(str));
		String str2 = editEnterShopRequest.getStart_time();
		str2 = str2.substring(11);
		shop.setOpenStartTime(Time.valueOf(str2));
		//经纬度
		shop.setLongitude(editEnterShopRequest.getLongitude());
		shop.setLatitude(editEnterShopRequest.getLatitude());
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", Long.valueOf(editEnterShopRequest.getId()));
		int line = shopService.update(shop);
		if(line<=0){
			return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR,"更新失败！");
		}
		
		return ResponseUtil.ok(editEnterShopResponse);
	}
	
	//@MagicPermission
	@ApiOperation(value = "关闭加盟店铺", notes = "关闭加盟店铺")
	@RequestMapping(value = "closeEnterShop", method = RequestMethod.POST)
	@ResponseBody
	public Response closeEnterShop(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody CloseEnterShopRequest closeEnterShopRequest){
		CloseEnterShopResponse closeEnterShopResponse = new CloseEnterShopResponse();
		logger.debug("关闭加盟店铺");
		Shop shop = new Shop();
		shop.setId(Long.valueOf(closeEnterShopRequest.getId()));
		shop.setStatus(4);
		
		int line = shopService.update(shop);
		if(line<=0){
			return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR,"关闭失败！");
		}
		
		return ResponseUtil.ok(closeEnterShopResponse);
	}
	
	//@MagicPermission
	@ApiOperation(value = "审核加盟店铺", notes = "审核加盟店铺")
	@RequestMapping(value = "checkEnterShop", method = RequestMethod.POST)
	@ResponseBody
	public Response checkEnterShop(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody CheckEnterShopRequest checkEnterShopRequest){
		//状态。 1: 等待审核 2: 审核已通过 3: 审核未通过 4: 已关闭'
		CheckEnterShopResponse checkEnterShopResponse = new CheckEnterShopResponse();
		logger.debug("审核加盟店铺");
		Shop shop = new Shop();
		
		List<Long> ids = checkEnterShopRequest.getIds();
		for (Long l : ids) {
			shop.setId(l);
			shop.setStatus(checkEnterShopRequest.getStatus());
			shop.setCheckDesc(checkEnterShopRequest.getReason());
			
			int line = shopService.update(shop);
			
			shop = new Shop();
			shop.setId(l);
			Shop shop2 = shopService.findOne(shop);
			
			if (checkEnterShopRequest.getStatus() ==2) {
				//生成消息
				Message message = new Message();
				message.setUserId(shop2.getUserId());
				message.setType(1);
				message.setPushType(1);
				message.setContent("恭喜您，你的加盟信息已审核通过！立即查看，点击“立即查看”进入“我的-我要加盟-我的店铺”页面");
				message.setCreateTime(new Timestamp(new Date().getTime()));
				message.setTitle("您的审核已通过");
				message.setRemark("审核已通过");
				//推送消息
				messageService.insert(message);
				//极光推送
				try {
					MsgPushUtils.addJPush(message.getContent(), shop2.getUserId().toString());
				} catch (APIConnectionException e) {
					e.printStackTrace();
				} catch (APIRequestException e) {
					e.printStackTrace();
				}
			}
			
			if (checkEnterShopRequest.getStatus() ==3) {
				//生成消息
				Message message = new Message();
				message.setUserId(shop2.getUserId());
				message.setType(1);
				message.setPushType(1);
				message.setContent("很抱歉，你的加盟信息审核失败，原因："+checkEnterShopRequest.getReason());
				message.setCreateTime(new Timestamp(new Date().getTime()));
				message.setTitle("您的审核未通过");
				message.setRemark("审核未通过");
				//推送消息
				messageService.insert(message);
				//极光推送
				try {
					MsgPushUtils.addJPush(message.getContent(), shop2.getUserId().toString());
				} catch (APIConnectionException e) {
					e.printStackTrace();
				} catch (APIRequestException e) {
					e.printStackTrace();
				}
			}
			
			if(line<=0){
				return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR,"ID 为"+l+"审核失败！");
			}
		}
		return ResponseUtil.ok(checkEnterShopResponse);
	}
	
	//@MagicPermission
	@ApiOperation(value = "查看店铺不通过原因", notes = "查看店铺不通过原因")
	@RequestMapping(value = "viewEnterShopRejectedReason", method = RequestMethod.POST)
	@ResponseBody
	public Response viewEnterShopRejectReason(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody ViewEnterShopRejectedReasonRequest viewEnterShopRejectedReasonRequest){
		ViewEnterShopRejectedReasonResponse viewEnterShopRejectedReasonResponse = new ViewEnterShopRejectedReasonResponse();
		logger.debug("查看店铺不通过原因");
		Shop shop = new Shop();
		shop.setId(viewEnterShopRejectedReasonRequest.getId());
		List<Shop> shops = shopService.find(shop);
		if(shops.size() != 1){
			return ResponseUtil.error("查看失败!");
		}
		String reason = shops.get(0).getCheckDesc();
		viewEnterShopRejectedReasonResponse.setReason(reason);
		return ResponseUtil.ok(viewEnterShopRejectedReasonResponse);
	}
	
	//@MagicPermission
	@ApiOperation(value = "获取店铺类型列表", notes = "获取店铺类型列表")
	@RequestMapping(value = "shopTypeList", method = RequestMethod.POST)
	@ResponseBody
	public Response shopTypeList(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody GetShopTypeListRequest getShopTypeListRequest){
		GetShopTypeListResponse getShopTypeListResponse = null;
		Map<String, Object> params = getPageMap(request);
		List<GetShopTypeListResponse> datas = new ArrayList<GetShopTypeListResponse>();
		logger.debug("获取店铺类型列表");
		ShopType shop = new ShopType();
		shop.setStartTime(getShopTypeListRequest.getStartTime());
		shop.setEndTime(getShopTypeListRequest.getEndTime());
		
		//分页
		
		long count = shopTypeService.count(params);
		
		int pageIndex = getShopTypeListRequest.getPageIndex_();
		int pageSize = getShopTypeListRequest.getPageSize_();
		Page<GetShopTypeListResponse> page = new Page<GetShopTypeListResponse>(pageIndex,pageSize);
		int limitStart = (pageIndex - 1) * pageSize;
		params.put("limitStart", limitStart);
		
		int limitEnd = pageSize;
		params.put("limitEnd", limitEnd);
		
		params.put("startTime", getShopTypeListRequest.getStartTime());
		params.put("endTime", getShopTypeListRequest.getStartTime());
		params.put("orderBy", "SHOP_TYPE.create_time desc");
		List<ShopType> listShop = shopTypeService.find(params);
		for(ShopType s : listShop){
			getShopTypeListResponse = new GetShopTypeListResponse();
			getShopTypeListResponse.setCreateTime(s.getCreateTime());
			getShopTypeListResponse.setLastEditTime(s.getUpdateTime());
			getShopTypeListResponse.setId(s.getId());
			//TODO lastEditTime  lastEditAdmin 字段没有添加
			getShopTypeListResponse.setLastEditAdmin("admin");
			getShopTypeListResponse.setLastEditTime(s.getUpdateTime());
			getShopTypeListResponse.setName(s.getName());
			datas.add(getShopTypeListResponse);
		}
		page.setData(datas);
		page.setTotalCount((int)count);
		return ResponseUtil.ok(page);
	}
	
	//@MagicPermission
	@ApiOperation(value = "添加店铺类型", notes = "添加店铺类型")
	@RequestMapping(value = "addShopType", method = RequestMethod.POST)
	@ResponseBody
	public Response addShopType(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody AddShopTypeRequest addShopTypeRequest){
		AddShopTypeResponse addShopTypeResponse = new AddShopTypeResponse();
		ShopType shopTpe = new ShopType();
		logger.debug("添加店铺类型");
		shopTpe.setName(addShopTypeRequest.getName());
		shopTpe.setCreateTime(new Timestamp((new Date()).getTime()));
		shopTpe.setEditUser("admin");
		if(!shopTypeService.insert(shopTpe)){
			return ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR,"添加店铺类型失败！");
		}
		return ResponseUtil.ok(addShopTypeResponse);
	}
	
	//@MagicPermission
	@ApiOperation(value = "编辑店铺类型", notes = "编辑店铺类型")
	@RequestMapping(value = "updateShopType", method = RequestMethod.POST)
	@ResponseBody
	public Response updateShopType(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody EditShopTypeRequest editShopTypeRequest){
		EditShopTypeResponse editShopTypeResponse = new EditShopTypeResponse();
		ShopType shopType = new ShopType();
		logger.debug("编辑店铺类型");
		shopType.setId(editShopTypeRequest.getId());
		shopType.setName(editShopTypeRequest.getName());
		shopType.setUpdateTime(new Timestamp((new Date()).getTime()));
		int i = shopTypeService.update(shopType);
		if (i<=0) {
			return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR,"编辑店铺类型失败！");
		}
		return ResponseUtil.ok(editShopTypeResponse);
	}
	
	//@MagicPermission
	@ApiOperation(value = "删除店铺类型", notes = "删除店铺类型")
	@RequestMapping(value = "deleteShopType", method = RequestMethod.POST)
	@ResponseBody
	public Response removeShopType(@CurrentUserId Long userId, HttpServletRequest request, HttpServletResponse response, @RequestBody DeleteShopTypeRequest deleteShopTypeRequest){
		DeleteShopTypeResponse deleteShopTypeResponse = new DeleteShopTypeResponse();
		ShopType shopType = new ShopType();
		logger.debug("删除店铺类型");
		shopType.setId(deleteShopTypeRequest.getId());
		shopTypeService.remove(shopType);
		return ResponseUtil.ok(deleteShopTypeResponse);
	}
	
	
	@ApiOperation(value = "获取门店加盟申请列表", notes = "获取门店加盟申请列表")
	@RequestMapping(value = "/storeApplicationList", method = RequestMethod.POST)
	@ResponseBody
	public Response storeApplicationList(@CurrentUserId Long userId, @RequestBody StoreApplication storeApplication){
		
		storeApplication.setOrderBy("STORE_APPLICATION.create_time DESC");
		storeApplication.setStatus(0);
		Page<StoreApplication> data = storeApplicationService.handlePage(storeApplication);
		
		return ResponseUtil.ok(data);
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public Response delete(@CurrentUserId Long userId,@RequestBody Shop shop){
		shop.setExist(1);
		shopService.update(shop);
		return ResponseUtil.ok();
	}
	
	@SuppressWarnings("unused")
	private SysConfig getSysConfig(String field) {
		SysConfig sysConfig = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params = new HashMap<String, Object>();
	 	params.put("field", field);
	 	sysConfig = sysConfigService.findOne(params);
		return sysConfig;
	}

}
